<template>
    <rx-dialog @handOk="handleCompleteCheck" @cancel="closeWindow" :oktext="this.$ti18('rxForm.commitBtn','提交')" order="buttom" btnalign="center">
        <rx-fit>
            <div style="height:100%;width:100%;padding:20px;">
                <a-form>
                    <a-form-item :label="i18n('form.specifyNodes','指定节点')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-select style="width: 100%" v-model="nodeId" :options="nodeAry"/>
                    </a-form-item>
                    <template v-if="nodeTypeMap[nodeId]!='batch'">
                      <a-form-item :label="i18n('form.approver','审批人')" :label-col="labelCol" :wrapper-col="wrapperCol">
                          <rx-user-component v-model="users" :single="false"></rx-user-component>
                      </a-form-item>
                      <a-form-item :label="i18n('form.approvalGroup','审批组')" :label-col="labelCol" :wrapper-col="wrapperCol">
                          <rx-group-component v-model="groups" :single="false"></rx-group-component>
                      </a-form-item>
                    </template>
                    <a-form-item :label="i18n('form.idea','意见')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-select
                            show-search
                            :value="value"
                            style="width: 200px"
                            :default-active-first-option="false"
                            :show-arrow="false"
                            :filter-option="false"
                            :not-found-content="null"
                            option-label-prop="label"
                            @search="handleSearch"
                            @change="handleChange"
                            @blur="handleBlur"
                            :placeholder="i18n('enterIdea','输入关键字搜索常用意见')"
                        >
                            <a-select-option v-for="d in data" :value="d.opText" :label="d.opText">
                                <a-icon type="close" @click.stop="closeOpinion(d)"></a-icon>
                                {{d.opText}}
                            </a-select-option>
                        </a-select>
                        <a-button style="margin-left: 3px;" @click="saveOpinion">{{$ti18('rxForm.saveBtn','保存')}}</a-button>
                        <a-textarea :placeholder="i18n('saveIdea','请填写意见，可保存为常用意见')" v-model="opinion"></a-textarea>
                    </a-form-item>

                    <a-form-item :label="i18n('form.appendix','附件')" :label-col="labelCol" :wrapper-col="wrapperCol">
                        <rx-attach-component v-model="fileList"></rx-attach-component>
                    </a-form-item>
                    <a-collapse defaultActiveKey="nodeUser" v-if="batchNodes.length>0" class="bpm-collapse">
                      <a-collapse-panel key="nodeUser" :header="i18n('instStart.assignBatchNodeFlowUsers','指定批次节点人员')">
                        <a-form-item
                            v-for="batchNode in batchNodes"
                            :key="batchNode.nodeId"
                            :label="batchNode.nodeName">
                          <div v-for="(batch,index) in batchNode.batchGroups" :class="{'bpm-item-div':true,'bpm-item-div-edit':batch.isNew}">
                            <div class="bpm-header-toolbar">
                              <div>
                                <a-input v-if="batch.isNew" v-model="batch.name" :placeholder="i18n('instStart.batchName','请输入批次名称','input')" />
                                <span v-else>{{batch.name}}</span>
                              </div>
                              <div class="bpm-toolbar-right">
                                <div class="bpm-toolbar-right-select">
                                  <a-select v-if="batch.isNew" v-model="batch.executeType" :options="executeOptions"  size='small' style="width:66px;"/>
                                  <a-tag v-else :color="executeTypeMap[batch.executeType].color">{{executeTypeMap[batch.executeType].text}}</a-tag>
                                </div>
                                <a-icon v-if="batchNode.batchOptions.includes('allowDel')" style="cursor: pointer;color:red;"
                                        :title="$ti18('rxList.delBtn','删除')" @click="removeBatch(batchNode,index)" type="delete"/>
                              </div>
                            </div>
                            <rx-user-component v-model="batch.users" :readonly="!batch.allowSelectUser" :single="false"></rx-user-component>
                          </div>
                          <div class="bpm-add-button-content" v-if="batchNode.batchOptions.includes('allowAdd')">
                              <span class="bpm-add-button" @click="addBatch(batchNode)">
                                  <a-icon type="plus-circle" />
                                  <span>{{i18n('instStart.newBatch','新增批次')}}</span>
                              </span>
                          </div>
                        </a-form-item>
                      </a-collapse-panel>
                    </a-collapse>
                </a-form>
            </div>
        </rx-fit>
    </rx-dialog>
</template>

<script>
    import {RxDialog, Util, RxFit, RxAttachComponent, RxUserComponent, RxGroupComponent} from "@lowcode/jpaas-common-lib"
    import BpmOpinionLibApi from "@/api/bpm/core/bpmOpinionLib";
    import BpmInstApi from "@/api/bpm/core/bpmInst";
    import BpmDefApi from "@/api/bpm/core/bpmDef";

    export default {
        name: "BpmInstLiveSelect",
        components: {
            RxAttachComponent,
            RxUserComponent,
            RxGroupComponent,
            RxFit,
            RxDialog
        },
        props: {
            layerid: String,
            destroy: Function,
            instId: {
                type: String,
                required: true
            }
        },
        data() {
            return {
                labelCol: {span: 4},
                wrapperCol: {span: 8},
                opinion: '',
                batchNodes:[],//批次节点
                value: undefined,
                fileList: [],
                data: [],
                nodeId: undefined,
                users: [],
                groups: [],
                nodeAry: [],
                nodeTypeMap:{},
                assignBatchFlowUsers:false,
                executeOptions:[
                  {value:"normal",label:this.i18n("instStart.normal","抢签")},
                  {value:"parallel",label:this.i18n("instStart.parallel","并行")},
                  {value:"sequential",label:this.i18n("instStart.sequential","串行")}
                ],
                executeTypeMap:{
                  normal:{color:"orange",text:this.i18n("instStart.normal","抢签")},
                  parallel:{color:"blue",text:this.i18n("instStart.parallel","并行")},
                  sequential:{color:"green",text:this.i18n("instStart.sequential","串行")}
                }
            }
        },
        created() {
            this.initAllNode();
            this.getBatchUserNodes();
            this.fetch('', data => (this.data = data));
        },
        methods: {
            i18n(name, text, key) {
                return this.$ti18(name, text, "bpmInst", key);
            },
            addBatch(batchNode){
              batchNode.batchGroups.push({isNew:true,name:"",executeType:"normal",condition:"",allowSelectUser:true,users:[]});
            },
            removeBatch(batchNode,index){
              batchNode.batchGroups.splice(index,1);
            },
            initAllNode() {
                var self=this;
                BpmInstApi.getAllNodes(this.instId).then(res => {
                    self.nodeAry = res.map(item => {
                        self.nodeTypeMap[item.nodeId]=item.multipleType;
                        return {label: item.nodeName, value: item.nodeId}
                    })
                })
            },
            closeWindow() {
                Util.closeWindow(this, 'cancel')
            },
            getBatchUserNodes() {
              var self=this;
              BpmDefApi.getBatchUserNodesByInstId(this.instId).then(resp => {
                self.batchNodes = [];
                self.assignBatchFlowUsers=resp.assignBatchFlowUsers;
                resp.data.forEach(item => {
                  let {options,groups}=item.batchGroup;
                  self.batchNodes.push({nodeId: item.nodeId, nodeName: item.name,allowExecutorNull:item.allowExecutorNull,i18nJson:item.i18nJson, batchOptions:options || [], batchGroups:groups || []});
                });
              });
            },
            handleCompleteCheck() {
                var userIds = [];
                for (var i = 0; i < this.users.length; i++) {
                    userIds.push(this.users[i].id);
                }
                var groupIds = [];
                for (var i = 0; i < this.groups.length; i++) {
                    groupIds.push(this.groups[i].id);
                }
                var data = {
                    destNodeUsers: JSON.stringify({
                        nodeId: this.nodeId,
                        userIds: userIds.join(','),
                        groupIds: groupIds.join(',')
                    }),
                    opinion: this.opinion,
                    opFiles: JSON.stringify(this.fileList)
                };
                if (this.assignBatchFlowUsers){
                  let batchNodeGroups = {};
                  for (let i = 0; i < this.batchNodes.length; i++) {
                    var node = this.batchNodes[i];
                    if(!node.allowExecutorNull && (node.batchGroups.length==0 || node.batchGroups[0].users.length==0)) {
                      this.$message.error(this.i18n('msa.batchNodeTips', '批次节点必须配置批次组人员！'));
                      return {success:false};
                    }
                    batchNodeGroups[node.nodeId] = node.batchGroups;
                  }
                  this.$set(data, 'batchNodeGroups', JSON.stringify(batchNodeGroups))
                }
                Util.closeWindow(this, 'ok', data)
            },
            handleSearch(value) {
                this.value = value;
                this.fetch(value, data => (this.data = data));
            },
            handleChange(value) {
                this.value = value;
            },
            handleBlur() {
                if (this.value) {
                    this.opinion = this.value;
                    this.value = undefined;
                }
            },
            saveOpinion() {
                var self = this;
                BpmOpinionLibApi.save({opText: this.value}).then(res => {
                    if (res.success) {
                        self.handleBlur();
                    }
                });
            },
            closeOpinion(opinion) {
                let self_ = this;
                this.$confirm({
                    title: this.$ti18('rxMsa.actionTips','操作提示'),
                    zIndex: 9999,
                    content: this.i18n('sureToClear','确定要删除此条意见吗？'),
                    okText: this.$ti18('rxForm.ackBtn','确认'),
                    cancelText: this.$ti18('rxForm.cancelBtn','取消'),
                    onOk() {
                        BpmOpinionLibApi.del({ids: opinion.opId}).then(res => {
                            self_.fetch('', data => (self_.data = data));
                        })
                    },
                    onCancel() {
                    }
                })
            },
            fetch(value, callback) {
                BpmOpinionLibApi.getUserText(value).then(res => {
                    callback(res);
                })
            }
        }
    }
</script>

<style scoped>

</style>